<template>
  <a-modal :open="open" width="880px" destroy-on-close title="填写快递信息" :footer="null" centered @cancel="onCancel">
    <div>
      <a-list :data-source="addrDataList">
        <template #renderItem="{ item }">
          <a-form
            class="form-style-flex form-style-flex2 border rounded mb-3 px-4 pt-2 pb-1 hover:bg-thin"
            :class="{ '!bg-secondary border-primary': selectRow.id === item.id }"
            @click="onSelect(item)"
          >
            <div class="flex mb-2 w-full justify-between">
              <div class="flex">
                <div class="mr-2">{{ item.contactName || '姓名' }}</div>
                <div class="mr-2">{{ item.provinceName ? `${item.provinceName}/${item.cityName}/${item.countyName}` : '地址' }}</div>
                <div v-if="item.id === '-1'" class="bg-primary text-white px-2">家庭地址</div>
              </div>
              <BaseIcon v-if="selectRow.id === item.id" name="CheckCircleFilled" :style="{ fontSize: '20px', color: 'var(--primary-color)' }" />
            </div>
            <a-form-item label="收货人:" class="w-1/2">
              <a-input v-if="item.isEdit" v-model:value="item.contactName" placeholder="请输入" />
              <span v-else>{{ item.contactName }}</span>
            </a-form-item>
            <a-form-item label="省市区" class="w-1/2">
              <SelectAddress
                v-if="item.isEdit"
                :value="item.provinceName ? `${item.provinceName}/${item.cityName}/${item.countyName}` : ''"
                allow-clear
                @change="(_, val) => onChangeAddress(item, val)"
              />
              <span v-else>{{ item.provinceName ? `${item.provinceName}/${item.cityName}/${item.countyName}` : '' }}</span>
            </a-form-item>
            <a-form-item label="详细地址" class="w-1/2">
              <a-input v-if="item.isEdit" v-model:value="item.addressDetail" placeholder="请输入" />
              <span v-else>{{ item.addressDetail }}</span>
            </a-form-item>
            <a-form-item label="联系方式" class="w-1/3">
              <a-input v-if="item.isEdit" v-model:value="item.contactPhone" v-input:int :maxlength="11" placeholder="请输入" />
              <span v-else>{{ item.contactPhone }}</span>
            </a-form-item>
            <div class="flex-1 flex justify-end items-center">
              <a-button v-if="item.isEdit" type="link" size="small" @click.stop="fetchSave(item)">保存</a-button>
              <a-button v-else type="link" size="small" @click.stop="item.isEdit = true">修改</a-button>
              <a-button v-if="item.id !== '-1'" type="text" size="small" danger @click.stop="onDelete(item)">删除</a-button>
            </div>
          </a-form>
        </template>
      </a-list>
    </div>
    <a-form :model="formState" class="form-style-flex">
      <a-form-item label="快递方式" class="w-1/2">
        <a-select
          v-model:value="formState.expressMode"
          :options="expressModeOptions"
          placeholder="请选择"
          :field-names="{ label: 'deliveryMethodName', value: 'deliveryMethodName' }"
          @change="onChangexpressMode"
        />
      </a-form-item>

      <a-form-item label="快递费:" class="w-1/2">
        <a-input v-model:value="formState.expressCost" v-input:float.2 placeholder="请输入">
          <template #prefix> <span class="text-gray-400">￥</span> </template>
        </a-input>
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.expressCmemo" :rows="3" placeholder="请输入" />
      </a-form-item>
    </a-form>
    <div class="flex justify-between mt-2">
      <!-- ok-text="保存" centered @ok="onOk" @cancel="onCancel" -->
      <div>
        <a-button type="link" @click="onNewAddress">新增收货地址</a-button>
      </div>
      <div>
        <a-button type="default" class="mr-4" @click="onCancel">取消</a-button>
        <a-button type="primary" @click="onOk">确认</a-button>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'ok'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  },
  brId: {
    type: String,
    default: ''
  }
})
const formState = ref({
  expressMode: null,
  expressCost: '',
  expressCmemo: ''
})
// const editItemId = ref('')
const addrDataList = ref([])
const selectRow = ref({})

const onOk = async () => {
  if (!formState.value.expressMode) {
    return message.error('请选择快递方式')
  }
  if (!selectRow.value.id) {
    return message.error('请选择地址')
  }
  emit('ok', { ...selectRow.value, ...formState.value })
  onCancel()
}
watch(
  () => props.open,
  (val) => {
    val && getAddrDataList()
    if (val && props.rowData.id) {
      formState.value = { ...props.rowData }
      selectRow.value = { ...props.rowData }
    }
  }
)
const expressModeOptions = ref([])
const getExpressMode = async () => {
  const { data, code } = await post('/operation/opex/getDeliveryMethodInfoList', {
    pageNum: 1,
    pageSize: 1000,
    status: '1'
  })
  if (code !== 0) return message.error('请求失败')
  expressModeOptions.value = data
}
const getAddrDataList = async () => {
  if (!props.brId) return
  const { data, code } = await post('/common/patient/getPatientAddressList', {
    brId: props.brId
  })
  if (code !== 0) return message.error('请求失败')
  addrDataList.value = data
  if (!selectRow.value.id) {
    selectRow.value = data[0] || {}
  }
}
const onChangexpressMode = (_, record) => {
  formState.value.expressCost = record?.dj
  formState.value.sfxmBh = record.sfxmBh
  formState.value.expressMode = record.sfxmmc
  formState.value.expressId = record.id
}
const onChangeAddress = (item, address) => {
  item.provinceName = address.data.province
  item.cityName = address.data.city
  item.countyName = address.data.county
}
const onCancel = () => {
  emit('update:open', false)
  // resetFields()
}
const onNewAddress = () => {
  addrDataList.value.push({
    isEdit: true,
    id: '',
    provinceName: '',
    cityName: '',
    countyName: ''
  })
}
// const isEditable = (item) => {
//   return editItemId.value === item.id || item.isNew
// }
const onDelete = (item) => {
  if (item.id) {
    fetchDelete(item)
  } else {
    addrDataList.value = addrDataList.value.filter((item) => item.id !== '')
    message.success('删除成功')
  }
}
const fetchDelete = async (item) => {
  const { code } = await post('/common/patient/doDelPatientAddress', {
    id: item.id
  })
  if (code !== 0) return message.error('请求失败')
  message.success('删除成功')
  getAddrDataList()
}
const fetchSave = async (item) => {
  if (!item.provinceName || !item.contactPhone || !item.contactName || !item.addressDetail) {
    return message.error('请填写完整')
  }
  const { code } = await post('/common/patient/doSavePatientAddress', {
    ...item,
    brId: props.brId
  })
  if (code !== 0) return message.error('请求失败')
  message.success('新增成功')
  // editItemId.value = false
  item.isEdit = false
  getAddrDataList()
}
const onSelect = (item) => {
  // if (editItemId.value === item.id) return
  if (item.isEdit) return
  selectRow.value = item
}
onMounted(() => {
  getExpressMode()
})
</script>
<style lang="less" scoped>
.form-style-flex2 {
  :deep(.ant-form-item) {
    margin-bottom: 4px;
    .ant-form-item-label > label {
      color: #afb5c1;
      &::after {
        content: ':';
      }
    }
  }
}
</style>
